<!-- 过站记录查询 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/cyx/mro/centerproduct/failure/page"
      :option="option"
      :page="page"
      :query="exportParams"
      file-name="不良统计"
    ></export-comp>
  </basic-container>
</template>

<script>
import { getList } from '@/api/report/failureStatistics';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
export default {
  name: 'failureStatistics',
  components: {
    exportComp,
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    var CreateTimeValidate = (rule, value, callback) => {
      if (value === null || value.length === 0) {
        callback(new Error('请选择时间范围'));
      } else if (value) {
        let transactionStartTime = this.$moment(value[0]).format('YYYY-MM-DD HH:mm:ss');
        let transactionEndTime = this.$moment(value[1]).format('YYYY-MM-DD HH:mm:ss');
        let transactionStartTimeGetTime = new Date(transactionStartTime).getTime();
        let transactionEndTimeGetTime = new Date(transactionEndTime).getTime();
        let monthTime = 24 * 3600 * 1000 * 30;
        if (transactionEndTimeGetTime - transactionStartTimeGetTime > monthTime) {
          callback(new Error('时间范围请选择一个月内'));
        } else {
          callback();
        }
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      exportParams: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 438px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        searchLabelWidth: 100,
        labelWidth: 120,
        menu: false,
        menuWidth: 100,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: false,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: '日期',
            width: 150,
            span: 12,
            prop: 'createTime',
            type: 'datetime',
            searchType: 'datetimerange',
            search: true,
            searchLabel: '时间范围',
            searchSpan: 8,
            searchFormat: 'yyyy-MM-dd HH:mm:ss',
            searchValueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            defaultTime: ['', '23:23:59'],
            searchRules: [
              {
                required: true,
                validator: CreateTimeValidate,
                trigger: 'blur'
              }
            ]
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            type: 'search',
            appendClick: () => {
              this.openWorkOrderNoModal();
            }
          },
          {
            label: '物料型号',
            prop: 'partModel',
            search: true
          },
          {
            label: '跳距',
            prop: 'skipDistance'
          },
          {
            label: '宽度',
            prop: 'width'
          },
          {
            label: '当日不良数',
            prop: 'failureCount'
          },
          {
            label: '穴数',
            prop: 'numberCavities'
          },
          {
            label: '不良面积',
            prop: 'area'
          },
          {
            label: '长度',
            prop: 'length'
          }
        ]
      },
      data: [],
      tableOption: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
    let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
    startDate = startDate + ' ' + '00:00:00';
    endDate = endDate + ' ' + '23:59:59';
    this.$set(this.search, 'createTime', [startDate, endDate]);
    this.query.createTime = this.search.createTime;
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.sequenceNumber && urlQuery.workOrderNo && urlQuery.passedDateTime && urlQuery.passedResult) {
        this.search.productSequenceNumber = decodeURIComponent(urlQuery.sequenceNumber);
        this.search.workOrderNo = decodeURIComponent(urlQuery.workOrderNo);
        this.search.result = decodeURIComponent(urlQuery.passedResult);
        let createTime = decodeURIComponent(urlQuery.passedDateTime).split(' ')[0];
        if (createTime) {
          this.search.createTime = [createTime + ' ' + '00:00:00', createTime + ' ' + '23:59:59'];
        }
      }
    });
    window.handleDownload = this.handleDownload;
    window.openPreview = this.openPreview;
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (this.search.createTime.length === 0) {
        return;
      }
      if (this.search.createTime.length > 0) {
        params.startTime = this.$moment(this.search.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        params.endTime = this.$moment(this.search.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTime;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    formatSeconds(value) {
      //  秒
      let second = parseInt(value);
      //  分
      let minute = 0;
      //  小时
      let hour = 0;
      //  天
      //  let day = 0
      //  如果秒数大于60，将秒数转换成整数
      if (second > 60) {
        //  获取分钟，除以60取整数，得到整数分钟
        minute = parseInt(second / 60);
        //  获取秒数，秒数取佘，得到整数秒数
        second = parseInt(second % 60);
        //  如果分钟大于60，将分钟转换成小时
        if (minute > 60) {
          //  获取小时，获取分钟除以60，得到整数小时
          hour = parseInt(minute / 60);
          //  获取小时后取佘的分，获取分钟除以60取佘的分
          minute = parseInt(minute % 60);
        }
      }

      let result = '' + parseInt(second) + '秒';
      if (minute > 0) {
        result = '' + parseInt(minute) + '分' + result;
      }
      if (hour > 0) {
        result = '' + parseInt(hour) + '小时' + result;
      }

      return result;
    },

    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleExport() {
      if (!(this.search.createTime && this.search.createTime.length)) {
        this.$message.error('请选择过站时间范围');
        return;
      }
      this.exportParams = this.getExportParam();
      this.$refs.exportComp.visible = true;
    },
    getExportParam() {
      const exportParams = this._cloneDeep(this.search);
      exportParams.startTime = this.$moment(exportParams.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
      exportParams.endTime = this.$moment(exportParams.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
      delete exportParams.createTime;
      return exportParams;
    },
    /**
     * 打开选择工单号模态框
     */
    openWorkOrderNoModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page?workOrderStatus=2,3',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /**
     * 获取选中工单号
     */
    getSelectedRows(rowData) {
      this.search.workOrderNo = this._get(rowData, 'orderNo', '');
    }
  }
};
</script>

<style scoped>
/*::v-deep .el-card .el-card__body .avue-crud__menu {*/
/*  display: none;*/
/*}*/
</style>
